package se.webbzon.oschi01.jinput;

import java.util.ArrayList;
import java.util.Collection;

import se.webbzon.boltzmann.debug.Debug;

import net.java.games.input.Controller;
import net.java.games.input.Event;
import net.java.games.input.EventQueue;

public class ControllerThread extends Thread {
	
	// The control associated with this polling thread
	private final Controller controller;
	
	// A collection of listeners to the control associated with this polling thread
	private Collection<ControllerEventListener> listeners;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Creates a new thread which polls a controller for data. **/
	public ControllerThread(Controller controller) {
		this.controller = controller;
		listeners = new ArrayList<ControllerEventListener>();
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Adds an event listener to the controller associated with this thread. **/
	public boolean addListener(ControllerEventListener listener) {
		return listeners.add(listener);
	}
	
	/** Removes an event listener from the controller associated with this thread. **/
	public boolean removeListener(ControllerEventListener listener) {
		return listeners.remove(listener);
	}
	
	/** Clears all listeners from the controller associated with this thread. **/
	public void clearListeners() {
		listeners.clear();
	}
	
	@Override public void run() {
		final Event event = new Event();
		while (true) {
			controller.poll();
			EventQueue queue = controller.getEventQueue();
			while (queue.getNextEvent(event)) {
				for (ControllerEventListener listener : listeners)
					listener.controllerChanged(controller,event);
			}
			
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				Debug.report(e);
				return;
			}
		}
	}

}
